{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Google Drive Tools\n",
    "\n",
    "The Google Drive integration in AG2 empowers users to seamlessly access and manage their files within the AG2 framework. With this integration, users can easily list, download, and interact with files stored in their Google Drive, providing a smooth and efficient way to handle documents, images, and other data in real time.\n",
    "\n",
    "## Installation\n",
    "\n",
    "Before using Google APIs, you need to enable them in your Google Cloud project. You can enable multiple APIs within a single project.\n",
    "\n",
    "1. Follow the [Setup environment](https://developers.google.com/workspace/drive/api/quickstart/python#set-up-environment) guide from Google Workspace to get started.\n",
    "2. Once you've completed the setup, you should have the `credentials.json` file downloaded to your local machine.\n",
    "3. Install AG2 with the `google-api` extra. Since our examples also use `openai`, install it as well:\n",
    "   \n",
    "    ```bash\n",
    "    pip install -U ag2[openai,google-api]\n",
    "    ```\n",
    "    > **Note:** If you have been using `autogen` or `ag2`, all you need to do is upgrade it using:  \n",
    "    > ```bash\n",
    "    > pip install -U autogen[openai,google-api]\n",
    "    > ```\n",
    "    > or  \n",
    "    > ```bash\n",
    "    > pip install -U ag2[openai,google-api]\n",
    "    > ```\n",
    "    > as `autogen`, and `ag2` are aliases for the same PyPI package.\n",
    "\n",
    "You're all set! Now you can start using Google Drive with AG2.\n",
    "\n",
    "## Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Annotated\n",
    "\n",
    "from autogen import AssistantAgent, LLMConfig\n",
    "from autogen.tools import tool\n",
    "from autogen.tools.experimental.google import GoogleCredentialsLocalProvider, GoogleDriveToolkit\n",
    "from autogen.tools.experimental.google.model import GoogleFileInfo"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Google Authentication\n",
    "\n",
    "Configure authentication to allow AG2 to access Google Drive:\n",
    "- `client_secret_file`: The path to the client secret file, which you can download from the Google Cloud Console. This file contains the necessary credentials to authenticate the user with Google services.\n",
    "- `token_file`: The path to a file that will store the access token. After the first run of the script, this token will be saved and used for subsequent authentications, avoiding the need for repeated login processes.\n",
    "- `provider` (`GoogleCredentialsLocalProvider`): The provider is responsible for managing the authentication process.\n",
    "- `credentials`: This variable stores the credentials object, which will be used by the system to authenticate the user and gain access to their Google Drive resources.\n",
    "\n",
    "> **Note:** The first execution opens a Google Authentication page in your browser."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "client_secret_file = \"../credentials.json\"\n",
    "token_file = \"../my_token.json\"\n",
    "\n",
    "provider = GoogleCredentialsLocalProvider(\n",
    "    client_secret_file=client_secret_file,\n",
    "    scopes=GoogleDriveToolkit.recommended_scopes(),\n",
    "    token_file=token_file,\n",
    ")\n",
    "\n",
    "credentials = provider.get_credentials()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Agent Configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "llm_config = LLMConfig.from_json(\n",
    "    path=\"OAI_CONFIG_LIST\",\n",
    ").where(model=\"gpt-5-nano\")\n",
    "\n",
    "assistant = AssistantAgent(name=\"assistant\", llm_config=llm_config)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Register Google Drive Tools\n",
    "\n",
    "The `GoogleDriveToolkit` class provides a set of predefined tools for seamless interaction with Google Drive. These tools include:\n",
    "- `list_drive_files_and_folders`: Allows the user to list all files and folders in their Google Drive.\n",
    "- `download_file_from_drive`: Enables downloading files directly from Google Drive to a specified local folder.\n",
    "\n",
    "Once the tool map is registered with the agent using `register_for_llm`, the agent becomes capable of suggesting these tool calls."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "google_drive_toolkit = GoogleDriveToolkit(\n",
    "    credentials=credentials,\n",
    "    download_folder=\"ag2_drive_downloads\",\n",
    ")\n",
    "\n",
    "google_drive_toolkit.register_for_llm(assistant)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Start the Conversation\n",
    "\n",
    "With the setup complete, you can now use the assistant to list and download files from your Google Drive."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "run_response = assistant.run(\n",
    "    message=\"\"\"Get me the last 3 files and download all docs/sheets/slides meme types.\n",
    "Ignore subfolders for now.\n",
    "Once done, write 'TERMINATE'.\"\"\",\n",
    "    max_turns=5,\n",
    "    tools=google_drive_toolkit.tools,\n",
    "    user_input=False,\n",
    ")\n",
    "run_response.process()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Custom GoogleDriveToolkit\n",
    "You can easily customize the predefined `GoogleDriveToolkit` based on your specific requirements. By subclassing `GoogleDriveToolkit`, you can modify the toolset available to your agent.\n",
    "\n",
    "For example:\n",
    "- **Add custom tools**: You can introduce new tools, like `list_docs`, to specifically retrieve document files from a folder.\n",
    "- **Remove existing tools**: You can eliminate unnecessary tools, such as `list_drive_files_and_folders`, to streamline functionality and focus on relevant features."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class MyGoogleDriveToolkit(GoogleDriveToolkit):\n",
    "    def __init__(\n",
    "        self,\n",
    "        *,\n",
    "        credentials,\n",
    "        download_folder,\n",
    "    ):\n",
    "        super().__init__(credentials=credentials, download_folder=download_folder)\n",
    "\n",
    "        # Define a custom tool\n",
    "        @tool(description=\"List documents in a folder\")\n",
    "        def list_docs(\n",
    "            page_size: Annotated[int, \"The number of files to list per page.\"] = 10,\n",
    "            folder_id: Annotated[\n",
    "                str | None,\n",
    "                \"The ID of the folder to list files from. If not provided, lists all files in the root folder.\",\n",
    "            ] = None,\n",
    "        ) -> list[GoogleFileInfo]:\n",
    "            doc_mime_types = [\n",
    "                \"application/vnd.google-apps.document\",  # Google Docs\n",
    "                \"application/pdf\",  # PDFs\n",
    "                \"application/msword\",  # MS Word\n",
    "                \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",  # DOCX\n",
    "            ]\n",
    "\n",
    "            mime_type_filter = \" or \".join(f\"mimeType='{mime}'\" for mime in doc_mime_types)\n",
    "            query = f\"({mime_type_filter}) and trashed=false\"\n",
    "\n",
    "            if folder_id:\n",
    "                query = f\"'{folder_id}' in parents and {query}\"\n",
    "\n",
    "            kwargs = {\n",
    "                \"pageSize\": page_size,\n",
    "                \"fields\": \"nextPageToken, files(id, name, mimeType)\",\n",
    "                \"q\": query,  # Apply filtering in the query itself\n",
    "            }\n",
    "\n",
    "            response = self.service.files().list(**kwargs).execute()\n",
    "            result = response.get(\"files\", [])\n",
    "\n",
    "            if not isinstance(result, list):\n",
    "                raise ValueError(f\"Expected a list of files, but got {result}\")\n",
    "\n",
    "            return [GoogleFileInfo(**file_info) for file_info in result]\n",
    "\n",
    "        # Remove tool which you don't want to use\n",
    "        self.remove_tool(\"list_drive_files_and_folders\")\n",
    "\n",
    "        # Add your custom tool\n",
    "        self.set_tool(list_docs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "assistant = AssistantAgent(name=\"assistant\", llm_config=llm_config)\n",
    "\n",
    "google_drive_toolkit = MyGoogleDriveToolkit(\n",
    "    credentials=credentials,\n",
    "    download_folder=\"ag2_drive_downloads\",\n",
    ")\n",
    "\n",
    "google_drive_toolkit.register_for_llm(assistant)\n",
    "\n",
    "run_response = assistant.run(\n",
    "    message=\"List the latest 3 files and write a short summary based on the file names and meme types.\",\n",
    "    max_turns=4,\n",
    "    tools=google_drive_toolkit.tools,\n",
    "    user_input=False,\n",
    ")\n",
    "run_response.process()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "front_matter": {
   "description": "Google Drive Tools",
   "tags": [
    "agents",
    "tools",
    "google drive"
   ]
  },
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
